package LeetCode.Arrays;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author : LdLtd
 * @Date : 2023/8/5
 * @Description:56. 合并区间
 */
public class merge_intervals {
    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] intervals= {{1,3},{15,18},{2,6},{8,10}};
        System.out.println(Arrays.deepToString(solution.merge(intervals)));
    }
   static class Solution {
        public int[][] merge(int[][] intervals) {
            //lambda
            Arrays.sort(intervals,(e1,e2)->e1[0]-e2[0]);

            // 使用Stream对二维数组按照 ar[i][0] 进行排序
//            int[][] sortedAr = Arrays.stream(intervals)
//                    .sorted(Comparator.comparingInt(a -> a[0]))
//                    .toArray(int[][]::new);
                //原始写法
//            Arrays.sort(intervals, new Comparator<int[]>() {
//                @Override
//                public int compare(int[] interval1, int[] interval2) {
//                    return interval1[0] - interval2[0];
//                }
//            });


            List<int[]> res = new ArrayList<>();
            int l=-1,r=-1;
            for (int[] ar : intervals) {
                if(ar[0]>r){
                    if(r!=-1)
                        res.add(new int[]{l,r});
                    l=ar[0];
                    r=ar[1];
                }
                else {
                    r=Math.max(r,ar[1]);
                }
            }
            if(r!=-1) res.add(new int[]{l,r});
            return res.toArray(new int[res.size()][2]);
        }
    }
}
